/*
 * 课程编辑
 */
import * as React from 'react';
import { connect } from 'react-redux';
import { createCourse, updateCourse } from 'actions/course';
import { get } from 'lodash';

import {
  Icon,
  Modal,
  Switch,
  Tooltip,
  InputNumber,
  Input,
  Button,
  message,
  Form,
  Select,
} from 'antd';

import CustomModal from 'components/common/CustomModal';
import { isLoading } from 'utils/utils';
import ACTIONS from 'constants/course';

import LoadableComponent from 'components/common/LoadableComponent';
const LoadableDragger = LoadableComponent(() => import('components/common/Dragger'));
const LoadableMedia = LoadableComponent(() => import('components/common/Media'));

import './Edit.scss';
import { attachment } from 'reducers';

const { Option } = Select;

/** 课程L级别 */
const COURSE_LEVEL = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

interface CourseEditProps {
  dispatch: (action: any) => any;
  onPublish: (checked: boolean) => any;
  onOk: () => any;
  onCancel: () => any;
  form: any;
  loadingGroup: any;
  editCourse: any;
}
interface CourseEditState {
  image: any;
}

class Edit extends React.Component<CourseEditProps, CourseEditState> {
  loadingKey: string;
  static defaultProps: CourseEditProps = {
    dispatch: () => {},
    onPublish: () => {},
    onOk: () => {},
    onCancel: () => {},
    form: {},
    loadingGroup: {},
    editCourse: null,
  };
  constructor(props: CourseEditProps) {
    super(props);

    this.loadingKey = props.editCourse ? ACTIONS.UPDATE : ACTIONS.CREATE;
    this.state = {
      image: get(props.editCourse, 'cover', null),
    };
  }

  handleSubmit = (e: any) => {
    e.preventDefault();

    const { editCourse } = this.props;
    const { form, dispatch, loadingGroup, onOk } = this.props;

    if (!isLoading(loadingGroup, this.loadingKey)) {
      form.validateFields((error: any, values: any) => {
        if (error) return;

        const action = editCourse ? updateCourse(editCourse.id, values) : createCourse(values);

        dispatch(action).then((result: any) => {
          if (result.code) {
            message.error(result.msg);
          } else {
            message.success('保存成功');
            onOk();
          }
        });
      });
    }
  };

  handleClose = () => {
    this.props.onCancel();
  };

  renderCover(attachment: any) {
    const { form } = this.props;
    if (attachment) {
      return (
        <div style={{ position: 'relative' }}>
          <LoadableMedia
            imageStyle={{ width: 300 }}
            attachment={attachment}
            onDestroy={() => {
              this.setState(
                {
                  image: null,
                },
                () => {
                  form.setFieldsValue({
                    cover: null,
                  });
                }
              );
            }}
          />
        </div>
      );
    }

    return (
      <LoadableDragger
        key="image"
        accept="image"
        selectMax={1}
        onDone={(response: any) => {
          const image = response.files[0];
          this.setState(
            {
              image,
            },
            () => {
              form.setFieldsValue({
                cover: image.id,
              });
            }
          );
        }}>
        <Button type="primary">
          <Icon type="picture" />
        </Button>
      </LoadableDragger>
    );
  }

  render() {
    const { image } = this.state;
    const { getFieldDecorator } = this.props.form;
    const { loadingGroup, editCourse, onPublish } = this.props;
    const title = editCourse ? '编辑课程' : '新增课程';
    const isPublished = Boolean(get(editCourse, 'isPublished', 0));

    const formItemLayout = {
      labelCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 5, offset: 2 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 16,
          offset: 8,
        },
      },
    };

    return (
      <CustomModal width={800} title={title} footer={false} onCancel={this.handleClose}>
        <Form onSubmit={this.handleSubmit}>
          <Form.Item {...formItemLayout} label="课程级别(Level)">
            {getFieldDecorator('level', {
              rules: [
                {
                  required: true,
                  message: '课程级别是必选项',
                },
              ],
              initialValue: get(editCourse, 'level', null),
            })(
              <Select
                disabled={Boolean(editCourse)}
                placeholder="请选择课程级别"
                style={{ width: '100%' }}>
                {COURSE_LEVEL.map((val: number) => {
                  return (
                    <Option key={val} value={val}>
                      L{val}
                    </Option>
                  );
                })}
              </Select>
            )}
          </Form.Item>
          <Form.Item {...formItemLayout} label="课程名称(内部识别)">
            {getFieldDecorator('name', {
              rules: [
                {
                  required: true,
                  message: '课程名称是必填项',
                },
              ],
              initialValue: get(editCourse, 'name', null),
            })(<Input placeholder="填写课程名称" />)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="课程描述(前端展示)">
            {getFieldDecorator('description', {
              rules: [
                {
                  required: true,
                  message: '课程描述是必填项',
                },
              ],
              initialValue: get(editCourse, 'description', null),
            })(
              <Input.TextArea
                autosize={{
                  minRows: 2,
                  maxRows: 6,
                }}
              />
            )}
          </Form.Item>
          <Form.Item {...formItemLayout} label="课时数量">
            {getFieldDecorator('lessonCount', {
              rules: [
                {
                  required: true,
                  message: '课时数量是必填项',
                },
              ],
              initialValue: get(editCourse, 'lessonCount', null),
            })(<Input placeholder="填写课时数量" />)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="单价(¥)">
            {getFieldDecorator('price', {
              rules: [
                {
                  required: true,
                  message: '课程单价是必填项',
                },
              ],
              initialValue: get(editCourse, 'price', null),
            })(<InputNumber style={{ width: '100%' }} placeholder="填写课程单价" />)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="优惠(¥)">
            {getFieldDecorator('discountPrice', {
              initialValue: get(editCourse, 'discountPrice', 0),
            })(<InputNumber style={{ width: '100%' }} placeholder="填写课程优惠金额" />)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="课程封面" style={{ verticalAlign: 'middle' }}>
            {getFieldDecorator('cover', {
              rules: [
                {
                  required: true,
                  message: '课程封面是必填项',
                },
              ],
              initialValue: get(image, 'id', null),
            })(this.renderCover(image))}
          </Form.Item>
          <Form.Item {...formItemLayout} label="发布：">
            <Switch
              loading={isLoading(loadingGroup, ACTIONS.UPDATE_PUBLISH_STATUS)}
              checked={isPublished}
              disabled={!editCourse}
              onChange={onPublish}
            />
          </Form.Item>
          <Form.Item {...tailFormItemLayout}>
            <Button size="large" onClick={this.handleClose}>
              取消
            </Button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <Button
              size="large"
              type="primary"
              htmlType="submit"
              loading={isLoading(loadingGroup, this.loadingKey)}>
              &nbsp;&nbsp;&nbsp;提交&nbsp;&nbsp;&nbsp;
            </Button>
          </Form.Item>
        </Form>
      </CustomModal>
    );
  }
}

// 父组件props传递的参数
interface OwnProps {
  editCourse: any;
}

function mapStateToProps(state: any, ownProps: OwnProps) {
  const { loadingGroup } = state;
  const { editCourse } = ownProps;

  return {
    loadingGroup,
    editCourse,
  };
}

export default connect(mapStateToProps)(Form.create()(Edit));
